<?php

namespace App\Console\Commands;

use App\Http\Controllers\Web\TianzhenlanController;
use App\Models\Company;
use App\Models\CompanyCity;
use App\Models\Goods;
use App\Utils\TianZhenLan;
use Illuminate\Console\Command;

class TongbuGoodsCity extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tb:goods-city';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步提供产品的城市列表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 将天真蓝的城市与我们的城市关联
        // self::tb_city_code();
        self::tb_goods_city();

        return 0;
    }

    static function tb_city_code() {
        $provinces = TianZhenLan::get_goods_cities('');
        foreach($provinces->items as $province) {
            foreach($province->children as $city) {

                $name = $city->name;
                $info = CompanyCity::where('company', Company::TZL)->where('city_name', $name)->first();
                if (!$info) {
                    echo $name. "不存在\n";    // 城市区域必须手动添加，因为不知道属于A/B/C的哪一类
                } else {
                    $info->city_code = $city->area_code;
                    $info->save();
                }
            }
        }
    }

    static function tb_goods_city() {

        $goods = Goods::where('company', Company::TZL)->get();
        foreach ($goods as $g) {
            if (!$g->gid) {
                continue;
            }
            $cites = TianZhenLan::get_goods_cities($g->gid);    // 查找产品在哪些城市开放
            $code = [];
            foreach($cites->items as $province) {
                foreach ($province->children as $city) {
                    array_push($code, $city->area_code);
                }
            }

            $cityIds = CompanyCity::where('company', Company::TZL)->whereIn('city_code', $code)->pluck('city_id')->toArray();
            $g->cities = implode(",", $cityIds);
            $g->save();
        }
    }
}
